package com.bw.controller.information;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.information.PiCustomer;
import com.bw.entity.information.PiLinkman;
import com.bw.entity.information.PiMaterial;
import com.bw.resp.ResponseResult;
import com.bw.service.information.IPiCustomerService;
import com.bw.service.information.IPiLinkmanService;
import com.bw.utils.excel.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelException;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-15
 */
@RestController
@RequestMapping("/information/pi-linkman")
public class PiLinkmanController {
    @Autowired
    private IPiLinkmanService iPiLinkmanService;

    private final Logger logger= LoggerFactory.getLogger(PiMaterialController.class);//日志
    @PostMapping("/add")
    public ResponseResult add(@RequestBody PiLinkman piLinkman){//添加联系人 参数1：定义需要的参数对象
        logger.info("联系人添加功能");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            piLinkman.setIsdelete(1);//默认删除为1（非删除标识）
            iPiLinkmanService.saveOrUpdate(piLinkman);//添加
            result.setMessage("操作成功");
            logger.info("添加成功");
        }catch (Exception e){
            logger.error("添加失败"+e.toString());
            result.setMessage("操作失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @PostMapping("/cxLinkMan/{id}")
    public ResponseResult cxCotumer(@PathVariable int id){//回显 参数1：需要查看的条件对象
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("回显联系人功能");
        try {
            PiLinkman piLinkman = iPiLinkmanService.getById(id);//根据获得到的id获取要回显的内容
            result.setResult(piLinkman);//存入result
            logger.info("回显成功，添加进返回集");
        }catch (Exception e){
            logger.error("查询失败"+e.toString());
            result.setMessage("查询失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @GetMapping("/detailById/{id}")
    public ResponseResult detailById(@PathVariable long id){//查看明细 参数1：定义一个接前端传值的对象
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("查看联系人明细功能");
        try {
            PiLinkman piLinkman = iPiLinkmanService.getById(id);//根据获得到的id获取要回显的内容
            result.setMessage("查看成功");
            result.setResult(piLinkman);
            logger.info("查询成功，结果存入返回集");
        }catch (Exception e){
            logger.error("查看失败"+e.toString());
            result.setMessage("查看失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @PostMapping("/list/{page}/{num}")
    public ResponseResult findList(@RequestBody PiLinkman piCustomer, @PathVariable int page,@PathVariable int num)throws Exception{//列表查询参数1：实体类对象。参数2：每页条数。参数3：开始页数
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("开始进行联系人列表查询");
        try {
            QueryWrapper wrapper = new QueryWrapper();
            logger.info("开启分页");
            PageHelper.startPage(num,page);//开启分页
            /*
             * 判断查询条件非空进行查询
             * */
            if(piCustomer.getCustomerId()!=null){//所属联系人id非空判断
                wrapper.eq("customerId",piCustomer.getCustomerId());
            }
            if(piCustomer.getSex()!=null){//性别非空判断
                wrapper.eq("sex",piCustomer.getSex());
            }
            if(piCustomer.getName()!=null && !"".equals(piCustomer.getName().trim())){//判断名称非null，以及去掉空格后非“”
                wrapper.like("name",piCustomer.getName());
            }
            if(piCustomer.getPosition()!=null){//职业非空判断
                wrapper.like("position",piCustomer.getPosition());
            }
            wrapper.eq("isdelete",1);//判断删除标识
            List list = iPiLinkmanService.list(wrapper);//根据提供的条件进行查询
            PageInfo pageInfo = new PageInfo<>(list);//将查询内容存到分页内容中
            result.setResult(pageInfo);//存入result
            logger.debug("查出所有内容，存入返回集");
        }catch (Exception e){
            logger.error("查询客户列表失败");
            result.setMessage("查询列表失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @DeleteMapping("/del/{ids}")
    public ResponseResult del(@PathVariable List<Integer> ids){//删除 参数1：定义数组获取前端传回的id数组
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("联系人信息删除功能");
        try {
            logger.debug("循环删除id的数组");
            for (int id:ids) {
                PiLinkman piLinkman = iPiLinkmanService.getById(id);
                piLinkman.setIsdelete(0); //根据所获取的id进行循环删除(改变删除标识)
                iPiLinkmanService.saveOrUpdate(piLinkman);//重新添加
            }
            result.setMessage("操作成功");
        }catch (Exception e){
            logger.error("删除失败");
            result.setMessage("删除失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @PostMapping("/importExcel")
    public ResponseResult importExcel(MultipartFile file){//导入 参数1：文件流
        logger.info("导入的xls");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());//获取后缀
            List<Map> mapList = ExcelUtil.readExcel(ext, file.getInputStream());//根据工具类读取到Excel所有内容
            logger.info("读取到Excel所有内容");
            String jsonString = JSON.toJSONString(mapList);//转为String类型
            List<PiLinkman> list = JSON.parseArray(jsonString, PiLinkman.class);//转为JSON格式
            logger.info("全部内容转为JSON格式");
            iPiLinkmanService.saveBatch(list);//批量添加
            logger.info("批量添加到数据库");
        }catch (Exception e){
            logger.error("导入失败"+e.toString());
            result.setMessage("导入失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException, ExcelException {//导出  参数1：对浏览器进行操作的response
        List<PiLinkman> list = iPiLinkmanService.list();
        /*
         * 定义导出的xls的格式
         * */
        logger.info("导出的xls");
        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("联系人数据".getBytes(),"iso-8859-1")+".xls");

        ClassPathResource classPathResource = new ClassPathResource("xls/linkMan.xls");//指向模板
        InputStream inputStream = classPathResource.getInputStream();//获取excel的模板

        ExcelUtils.addValue("list",list);//存入数据
        logger.info("向模板存值");

        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());//第一个参数：模板的流。第三个：输出到哪
        logger.info("输出Excel");

    }
    @GetMapping("/cxLinkmanByCustomerId/{id}")
    public ResponseResult cxLinkman(@PathVariable Integer id){//删除 参数1：定义数组获取前端传回的id数组
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("查询联系人功能");
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("customerId",id);
            List list = iPiLinkmanService.list(wrapper);
            result.setResult(list);
        }catch (Exception e){
            logger.error("查询联系人失败");
            result.setMessage("查询联系人失败"+e.toString());
            result.setSuccess(false);
        }
        return result;

    }
}
